﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MailS;

public partial class Move_User_Inform : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string condition = "";      
        string pronum = Session["pro_num"].ToString();

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringProManage"].ConnectionString;
        try
        {
            conn.Open();
            //读仪器名称
            string SQLc = "select condition from Products where pro_num=@pronum";
            SqlCommand cmdc = new SqlCommand();
            cmdc.Connection = conn;
            cmdc.CommandType = CommandType.Text;
            cmdc.CommandText = SQLc;
            SqlParameter p1 = new SqlParameter("@pronum", pronum);
            cmdc.Parameters.Add(p1);
            //cmdimg.ExecuteNonQuery();
            condition = cmdc.ExecuteScalar().ToString();

            if (condition == "正常")
            {
                BtSubmit.Enabled = true;
            }
            else
            {
                BtSubmit.Enabled = false;
            }
            string tabelrep = "<table class='layui-table'><thead> <tr><td colspan='8' style='background-color: #EEE;font-size:large;text-align:center'>该设备的报修维修记录</td></tr><tr><th>报修时间</th><th>报修原因</th><th>维修时间</th><th>维修过程</th></tr></thead>";
            string SQLrep = "select date_inform,rep_cause,date_rep,rep_program from Repair where (pro_num=@pronum and flag=1)";
            SqlCommand cmdrep = new SqlCommand();
            cmdrep.Connection = conn;
            cmdrep.CommandType = CommandType.Text;
            cmdrep.CommandText = SQLrep;
            SqlParameter p4 = new SqlParameter("@pronum", pronum);
            cmdrep.Parameters.Add(p4);
            using (SqlDataReader readerrep = cmdrep.ExecuteReader())
            {
                int fieldcount = readerrep.FieldCount;      //取字段总数
                if (!readerrep.HasRows)            //有数据  ---行
                {
                    LabelRepair.Text = "<table class='layui-table' style='width: 70%; margin-left:15% '><tr><td>此仪器没有报修维修记录</td></tr>";
                }
                else
                {
                    string trd = "<tbody>";                     //存储数据
                    while (readerrep.Read())               //当有数据可读时
                    {
                        trd += "<tr>";         //数据行开始，行以tr起
                        for (int i = 0; i < fieldcount; i++)
                        {   //每一列的内容
                            trd += "<td>" + readerrep[i].ToString() + "</td>";
                        }
                        //行结束
                    }

                    LabelRepair.Text = tabelrep + trd + "</tbody></table>";
                }
            }
        }

        finally
        {
            conn.Close();
        }
    }

    protected void BtSubmit_Click(object sender, EventArgs e)
    {
        string place = "";
        string date0 = DateTime.Now.ToString("yyyy-MM-dd");
        string time = DateTime.Now.ToLongTimeString().ToString();
        string date = date0 + " " + time;
        string pronum = Session["pro_num"].ToString();
        string cause = FRepair.Text;
        //int flag = 0;
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringProManage"].ConnectionString;
        try
        {
            conn.Open();
            string SQLp = "select pro_location from Products where pro_num=@pronum";
            SqlCommand cmdp = new SqlCommand();
            cmdp.Connection = conn;
            cmdp.CommandType = CommandType.Text;
            cmdp.CommandText = SQLp;
            SqlParameter p2 = new SqlParameter("@pronum", pronum);
            cmdp.Parameters.Add(p2);
            place = cmdp.ExecuteScalar().ToString();

            string SQLr = "insert into Repair (pro_num,pro_location,date_inform,rep_cause) values (@pro_num,@pro_location,@date_inform,@rep_cause)";
            SqlCommand cmdr = new SqlCommand();
            cmdr.Connection = conn;
            cmdr.CommandType = CommandType.Text;
            cmdr.CommandText = SQLr;

            SqlParameter ppronum = new SqlParameter("@pro_num", SqlDbType.NVarChar, 10);
            ppronum.Value = pronum;
            cmdr.Parameters.Add(ppronum);
            SqlParameter pplace = new SqlParameter("@pro_location", SqlDbType.NVarChar, 20);
            pplace.Value = place;
            cmdr.Parameters.Add(pplace);
            SqlParameter pdate = new SqlParameter("@date_inform", SqlDbType.NVarChar, 20);
            pdate.Value = date;
            cmdr.Parameters.Add(pdate);
            SqlParameter pcause = new SqlParameter("@rep_cause", SqlDbType.NVarChar, 100);
            pcause.Value = cause;
            cmdr.Parameters.Add(pcause);
            //cmdr.ExecuteNonQuery();
            int R = cmdr.ExecuteNonQuery();  //R 的值就是返回影响表的行数
            if (R > 0)
            {
                Session["ReturnPath"] = "Move_User_AttView.aspx";
                Session["Message"] = "报修成功，我们会尽快处理！";

                //仪器状态修改
                string SQL = "update Products set [condition]=@condition where [pro_num]=@pro_num";
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = SQL;
                SqlParameter pc = new SqlParameter("@condition", SqlDbType.NVarChar, 10);
                pc.Value = "待维修";
                cmd.Parameters.Add(pc);
                SqlParameter ppro_num = new SqlParameter("@pro_num", SqlDbType.NVarChar, 10);
                ppro_num.Value = pronum;
                cmd.Parameters.Add(ppro_num);
                cmd.ExecuteNonQuery();

                string SqlGetBookingTime = "select book_id,phone_num,date,time from booking where condition=N'预约成功' and flag=1 and pro_num=@pro_num";
                string BookingTime = "";          //数据库读取的时间段
                string SubBookingTime = "";       //数据库读取的时间取起始时间
                string BookingDate = "";          //数据库读取的日期
                string BookingDateSum = "";       //数据库读取的日期加起始时间
                string BookingTimeSpan = "";      //数据库读取的时间加时间段（放在邮件里的）
                DateTime ConvertBookingDateSum = new DateTime();
                //string Pro_Num = "";
                string Phone_Num = "";
                string BookingIdSum = "";

                string useremail = "";
                string username = "";
                //string userdevicenum = "";
                string title = "";
                string body = "";

                SqlCommand CmdGetBookingTime = new SqlCommand();
                CmdGetBookingTime.Connection = conn;
                CmdGetBookingTime.CommandType = CommandType.Text;
                CmdGetBookingTime.CommandText = SqlGetBookingTime;
                SqlParameter pppro_num = new SqlParameter("@pro_num", SqlDbType.NVarChar, 10);
                pppro_num.Value = pronum;
                CmdGetBookingTime.Parameters.Add(pppro_num);
                using (SqlDataReader reader = CmdGetBookingTime.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Phone_Num += reader["phone_num"].ToString()+"|";
                        BookingDate = reader["date"].ToString();
                        BookingTime = reader["time"].ToString();
                        SubBookingTime = BookingTime.Substring(0, 5);
                        BookingTimeSpan += BookingDate + " " + BookingTime+"|";
                        BookingDateSum +=BookingDate+" "+SubBookingTime+"|";
                        BookingIdSum += reader["book_id"].ToString()+"|";

                        //ConvertBookingDateSum = System.Convert.ToDateTime(BookingDateSum);
                        //if (ConvertBookingDateSum>=DateTime.Now)
                        //{
                        //    string Sqlgetusermail = "select name,email from users where tel=@usertel and flag=1";
                        //    SqlCommand sqlcmdgetusermail = new SqlCommand();
                        //    sqlcmdgetusermail.Connection = conn;
                        //    sqlcmdgetusermail.CommandText = Sqlgetusermail;
                        //    sqlcmdgetusermail.CommandType = CommandType.Text;
                        //    SqlParameter pusertel = new SqlParameter("@usertel", SqlDbType.VarChar, 11);
                        //    pusertel.Value = Phone_Num;
                        //    sqlcmdgetusermail.Parameters.Add(pusertel);
                        //    using (SqlDataReader reader1 = sqlcmdgetusermail.ExecuteReader())
                        //    {
                        //        while (reader1.Read())
                        //        {
                        //            useremail = reader1["email"].ToString();
                        //            username = reader1["name"].ToString();
                        //            title = "[设备维修提醒]";
                        //            body = "尊敬的 " + username + " 先生/女士，由于您预约的编号为 " + pronum + " 的设备损坏,因此可能会导致您在您的预约时间(" + BookingDate + " " + BookingTime + ")内无法使用该设备；如在您的预约时间前设备维修完成，那么我们会保留您的预约信息，并另行通知，不便之处敬请谅解！";
                        //            EmailS.SendingMail(useremail, title, body);

                        //        }
                        //    }
                        //}

                    }
                }
                string[] SinglePhone_NUM = Phone_Num.Split('|');
                string[] SingleBookingDateSum = BookingDateSum.Split('|');
                string[] SingleBookingTimeSpan = BookingTimeSpan.Split('|');
                string[] SingleBookingIdSum = BookingIdSum.Split('|');
                for (int i = 0; i < SinglePhone_NUM.Length-1; i++)
                {
                    ConvertBookingDateSum = System.Convert.ToDateTime(SingleBookingDateSum[i]);
                    if (ConvertBookingDateSum>=DateTime.Now)
                    {
                        string Sqlgetusermail = "select name,email from users where tel=@usertel and flag=1";
                        SqlCommand sqlcmdgetusermail = new SqlCommand();
                        sqlcmdgetusermail.Connection = conn;
                        sqlcmdgetusermail.CommandText = Sqlgetusermail;
                        sqlcmdgetusermail.CommandType = CommandType.Text;
                        SqlParameter pusertel = new SqlParameter("@usertel", SqlDbType.VarChar, 11);
                        pusertel.Value = SinglePhone_NUM[i];
                        sqlcmdgetusermail.Parameters.Add(pusertel);
                        using (SqlDataReader reader1 = sqlcmdgetusermail.ExecuteReader())
                        {
                            while (reader1.Read())
                            {
                                useremail = reader1["email"].ToString();
                                username = reader1["name"].ToString();
                                title = "[设备维修提醒]";
                                body = "尊敬的 " + username + " 先生/女士，由于您预约的编号为 " + pronum + " 的设备损坏,因此可能会导致您在您的预约时间(" + SingleBookingTimeSpan[i] + ")内无法使用该设备。如在您的预约时间前设备维修完成，那么我们会保留您的预约信息，并另行通知；若到了您预约的时间您还没有收到相关通知，则说明设备还未修好，烦请您对维修状态保持关注，并在修好后重新预约，不便之处敬请谅解！";
                                EmailS.SendingMail(useremail, title, body);

                            }
                        }

                        //string SqlUpdateFlag = "update Booking set flag=0 where book_id=@book_id";
                        //SqlCommand SqlCmdUpdateFlag = new SqlCommand();
                        //SqlCmdUpdateFlag.Connection = conn;
                        //SqlCmdUpdateFlag.CommandType = CommandType.Text;
                        //SqlCmdUpdateFlag.CommandText = SqlUpdateFlag;
                        //SqlParameter pbook_id = new SqlParameter("@book_id", SqlDbType.Int);
                        //pbook_id.Value = Convert.ToInt32(SingleBookingIdSum[i]);
                        //SqlCmdUpdateFlag.Parameters.Add(pbook_id);
                        //SqlCmdUpdateFlag.ExecuteNonQuery();


                    }
                    
                }
                

                //更新flag



                //Phone_Num = reader["phone_num"].ToString();
                //BookingDate = reader["date"].ToString();
                //BookingTime = reader["time"].ToString();
                //SubBookingTime = BookingTime.Substring(0, 5);
                //BookingDateSum = BookingDate + " " + SubBookingTime;
                //ConvertBookingDateSum = System.Convert.ToDateTime(BookingDateSum);
                //if (ConvertBookingDateSum >= DateTime.Now)
                //{
                    
                //}


                Response.Redirect("Success.aspx");
                //flag = 1;
              
            }
            else
            {
                Session["Message"] = "报修失败";
                Response.Redirect("Error.aspx");
            }
            //if (flag == 1)
            //{
                
            //}           
        }
        finally
        {
            conn.Close();
        }
    }
}